﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using System.Windows.Resources;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using InTheHand.ApplicationModel.DataTransfer.ShareTarget;

namespace InTheHand.ApplicationModel.DataTransfer
{
    internal partial class SharePage : PhoneApplicationPage
    {
        ObservableCollection<IShareTarget> targets = new ObservableCollection<IShareTarget>();

        public SharePage()
        {
            InitializeComponent();

            ShareHeader.Text = InTheHand.ApplicationModel.DataTransfer.Resources.Resources.ShareHeader;

            ShareTargetList.ItemsSource = targets;
            ShareTargetList.SelectionChanged += ShareTargetList_SelectionChanged;
        }

        void ShareTargetList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (ShareTargetList.SelectedItem != null)
            {
                IShareTarget target = (IShareTarget)ShareTargetList.SelectedItem;
                DataTransferManager.GetForCurrentView().OnTargetApplicationChosen(new TargetApplicationChosenEventArgs(target.DisplayName));
                target.OnShareTargetActivated(new ShareOperation(DataTransferManager.GetForCurrentView().currentDataPackage.GetView()));

            }
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            if (e.NavigationMode == NavigationMode.Back)
            {
                if (NavigationService.CanGoBack)
                {
                    NavigationService.GoBack();
                }
                return;
            }

            // determine share types supported by available data
            try
            {
                NfcShare ns = new NfcShare();
                if (ns.CanShare(DataTransferManager.GetForCurrentView().currentDataPackage.GetView()))
                {
                    targets.Add(ns);
                }

            }
            catch { }

            targets.Add(new MessagingShare());
            targets.Add(new EmailShare());
            targets.Add(new SocialShare());
            // targets.Add(new ClipboardShare());

            base.OnNavigatedTo(e);
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            targets.Clear();

            base.OnNavigatedFrom(e);


        }
    }

}